package com.gly091020.client;

import com.gly091020.EnglishFight;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;
import net.fabricmc.fabric.api.client.rendering.v1.HudRenderCallback;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.gui.DrawContext;
import net.minecraft.enchantment.EnchantmentHelper;
import net.minecraft.text.Text;

@Environment(EnvType.CLIENT)
public class ComboHudRenderer implements HudRenderCallback {
    private static int currentCombo = 0;
    private static int maxCombo = 10; // 默认最大连击数

    // Combo条配置
    private static final int BAR_WIDTH = 20;
    private static final int BAR_HEIGHT = 100;
    private static final int BAR_X = 10;
    private static final int BAR_Y = 50;
    private static final int TEXT_OFFSET = 25;

    @Override
    public void onHudRender(DrawContext drawContext, float tickDelta) {
        if (currentCombo <= 0) return;
        if (MinecraftClient.getInstance().player == null){return;}
        if (EnchantmentHelper.getLevel(EnglishFight.ENGLISH_FIGHT,
                MinecraftClient.getInstance().player.getMainHandStack()) == 0){return;}

        float progress = Math.min((float) currentCombo / maxCombo, 1.0f);
        int color = getGradientColor(progress);

        // 绘制背景
        drawContext.fill(BAR_X, BAR_Y, BAR_X + BAR_WIDTH, BAR_Y + BAR_HEIGHT, 0x80000000);

        // 绘制填充条
        int filledHeight = (int) (BAR_HEIGHT * progress);
        drawContext.fill(BAR_X, BAR_Y + (BAR_HEIGHT - filledHeight),
                BAR_X + BAR_WIDTH, BAR_Y + BAR_HEIGHT,
                color);

        // 绘制边框
        drawContext.drawBorder(BAR_X, BAR_Y, BAR_WIDTH, BAR_HEIGHT, 0xFFFFFFFF);

        // 绘制连击数文本
        Text text = Text.literal(currentCombo + "x");
        drawContext.drawText(MinecraftClient.getInstance().textRenderer,
                text,
                BAR_X + TEXT_OFFSET,
                BAR_Y + BAR_HEIGHT / 2 - 4,
                0xFFFFFF,
                true);
    }

    private int getGradientColor(float progress) {
        // 红(0%:FF0000) -> 黄(50%:FFFF00) -> 绿(100%:00FF00)
        if (progress < 0.5f) {
            return 0xFF << 24 | 255 << 16 | ((int)(255 * progress * 2) << 8);
        } else {
            return 0xFF << 24 | ((int)(255 * (1 - (progress - 0.5f) * 2)) << 16) | 255 << 8;
        }
    }

    // 外部调用的静态方法
    public static void setCombo(Integer v) {
        currentCombo = v;
    }

    public static void setMaxCombo(int max) {
        maxCombo = max;
    }

    // 注册方法
    public static void register() {
        HudRenderCallback.EVENT.register(new ComboHudRenderer());
    }
}